package com.dhq.myapp.base.adapter

import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import java.util.Collections

/**
 * DESC RecycleView 的公用adapter
 * Created by admin on 2016/9/6.
 */
abstract class RvBaseAdapter<T>(private val layoutId: Int) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    protected val datas = ArrayList<T>()

    /**
     * 设置列表数据
     *
     * @param datas 列表数据
     */
    fun setDatas(datas: List<T>?) {
        this.datas.clear()
        if (datas == null) {
            return
        }
        this.datas.addAll(datas)
        notifyDataSetChanged()
    }

    /**
     * 添加单个数据
     *
     * @param data 列表数据
     */
    fun addData(data: T) {
        datas.add(data)
        notifyDataSetChanged()
    }

    /**
     * 添加单个数据到一个位置
     *
     * @param data 列表数据
     */
    fun addData(data: T, position: Int) {
        datas.add(position, data)
        notifyItemInserted(position)
    }

    /**
     * 添加多个数据
     *
     * @param datas 要添加的多个数据
     */
    fun addDatas(datas: List<T>?) {
        if (datas == null) {
            return
        }
        this.datas.addAll(datas)
        notifyDataSetChanged()
    }

    /**
     * 移除单个item
     *
     * @param position 要移除的item下标
     */
    fun removeData(position: Int) {
        datas.removeAt(position)
//        notifyItemRemoved(position)
        notifyDataSetChanged()
    }

    fun getDatas(): List<T> = datas

    fun getData(position: Int): T = datas[position]

    /**
     * 拖拽交换数据
     *
     * @param dragPosition   拖拽的item下标
     * @param targetPosition 要交换的item的下标
     */
    fun changeItem(dragPosition: Int, targetPosition: Int) {
        Collections.swap(datas, dragPosition, targetPosition)
        notifyItemMoved(dragPosition, targetPosition)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(layoutId, parent, false)
        return RvBaseHolder(view, viewType)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        convert(this, holder as RvBaseHolder, datas[position], position)
    }

    override fun getItemCount(): Int = datas.size

    abstract fun convert(adapter: RvBaseAdapter<T>, holder: RvBaseHolder, item: T, position: Int)
}